package com.mgq.netty.chat.protocol;

import com.mgq.netty.chat.config.ConfigProperties;
import com.mgq.netty.chat.message.LoginRequestMessage;
import com.mgq.netty.chat.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author MaGuangQi
 * @description
 * @date 2021-12-09 16:29
 **/
public class TestSerializer {
    public static void main(String[] args) {
        LoggingHandler LOG_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecShare MES_CODEC = new MessageCodecShare();
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(LOG_HANDLER,MES_CODEC,LOG_HANDLER);
        LoginRequestMessage loginRequestMessage = new LoginRequestMessage("zhangsan", "123");

        //embeddedChannel.writeOutbound(loginRequestMessage);
        ByteBuf byteBuf = messageToByteBuf(loginRequestMessage);
        embeddedChannel.writeInbound(byteBuf);

        //测试出站


    }

    private static ByteBuf messageToByteBuf(Message msg) {
        int ordinal = ConfigProperties.getSerializerAlgorithm().ordinal();
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        // 4个字节的魔数
        out.writeBytes(new byte[]{1,2,3,4});
        //1个字节的版本号
        out.writeByte(1);
        //1个字节的序列化算法: 0 jdk,1.json
        out.writeByte(ordinal);
        //1个字节的指令类型
        out.writeByte(msg.getMessageType());
        //4个字节的请求序号
        out.writeInt(msg.getSequenceId());
        //5.填充1个字节,凑够16个字节
        out.writeByte(0xff);
        //正文长度
        byte[] bytes = Serializer.Algorithm.values()[ordinal].serialize(msg);
        //长度用4个字节
        out.writeInt(bytes.length);
        //写入消息正文
        out.writeBytes(bytes);
        return out;
    }
}
